package com.situ.scientific.servlet;


import com.situ.scientific.pojo.Auth;
import com.situ.scientific.pojo.Researchers;
import com.situ.scientific.pojo.query.ResearchersQuery;
import com.situ.scientific.pojo.vo.ResearchIdVo;
import com.situ.scientific.service.IAuthService;
import com.situ.scientific.service.IResearchersService;
import com.situ.scientific.service.impl.AuthserviceImpl;
import com.situ.scientific.service.impl.ResearchersServiceImpl;
import com.situ.scientific.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/researchers")
public class ResearchersServlet extends HttpServlet {
    IResearchersService researchersService = new ResearchersServiceImpl();
    IAuthService authService = new AuthserviceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if (method==null||method.equals("")){
            method = "selectByPage";
        }
        switch (method){
            case "selectByPage":
                selectByPage(req,resp);
                break;
            case "deleteById":
                deleteById(req,resp);
                break;
            /*case "deleteAll":
                deleteAll(req,resp);
                break;*/
            case "add":
                add(req,resp);
                break;
           case "selectById":
                selectById(req,resp);
                break;
            case "update":
                update(req,resp);
                break;
            /*case "updateStatus":
                updateStatus(req,resp);
                break;*/
            case "exportExcel":
                exportExcel(req,resp);
                break;
            case "importExcel":
                importExcel(req,resp);
                break;
            case "login":
                login(req,resp);
                break;
        }
    }

    private void importExcel(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.importExcel");
        researchersService.importExcel(req);
        JSONUtil.toJSON(resp, Result.ok("导入成功"));
    }

    private void exportExcel(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.exportExcel");
        //调用service层
        List<Researchers> list = researchersService.selectAll();
        ExcelUtil.exportExcel(resp,list, Researchers.class,"researchers");
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.deleteAll");
        //传过来的是一个id的数组
        String[] ids = req.getParameterValues("ids[]");
        System.out.println(ids);
        //收到了传过来的id值，然后调用service
        researchersService.deleteAll(ids);
        Result result = new Result(0,"删除成功");
        JSONUtil.toJSON(resp,result);
    }

    /*private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.updateStatus");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        researchersService.updateStatus(id,Integer.parseInt(status));
        JSONUtil.toJSON(resp,Result.ok("更新成功"));
    }*/

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.update");
        Researchers researchers = MyBeanUtil.copyToBean(req, Researchers.class);
        researchersService.update(researchers);
        Result result = new Result(0,"修改成功");
        JSONUtil.toJSON(resp,result);
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.selectById");
        //String id = req.getParameter("id");
        HttpSession session = req.getSession();
        Researchers researchers = (Researchers) session.getAttribute("researchers");
        Integer id = researchers.getId();
        //List<ResearchersQuery> list = researchersService.selectByPage();//这个是找下拉框的
        //我得在用个Vo把数据封装一下
        ResearchIdVo researchIdVo = researchersService.selectById(String.valueOf(id));//返回的肯定不是researchers
        Map<String,Object> map = new HashMap<>();
        //map.put("list",list);
        map.put("researchIdVo",researchIdVo);
        System.out.println("servlet中:"+researchIdVo);
        JSONUtil.toJSON(resp,Result.ok(map));

    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.add");
        /*String name = req.getParameter("name");
        System.out.println(name);*/
        //封装一下

        Researchers researchers = MyBeanUtil.copyToBean(req, Researchers.class);
        System.out.println(researchers);
        researchersService.add(researchers);
        //返回Ajax数据
        Result result = new Result(0,"添加成功");
        JSONUtil.toJSON(resp,result);
    }

    /*private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("ResearchersServlet.deleteAll");
        String[] ids = req.getParameterValues("ids[]");
        //得到数组之后调用service层函数
        researchersService.deleteAll(ids);
        //然后返回json数据
        Result result = new Result(0,"删除成功");
        JSONUtil.toJSON(resp,result);
        *//*resp.setContentType("text/html;charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(resp.getWriter(), result);*//*
    }*/

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("ResearchersServlet.deleteById");
        //接收参数
        String id = req.getParameter("id");
        System.out.println("id:"+id);
        //调用函数
        int count = researchersService.deleteById(Integer.parseInt(id));//没有返回值
        Result result = null;
        if (count>0){
            result = new Result(0,"删除成功");
        }else {
            result = new Result(1,"删除失败");
        }
        //固定的三行
        JSONUtil.toJSON(resp,result);
        //*resp.setContentType("text/html;charset=UTF-8");
        //ObjectMapper mapper = new ObjectMapper();
       //mapper.writeValue(resp.getWriter(), result);//*//现在不知道这里要返回什么
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("ResearchersServlet.selectByPage");
        /*String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String name = req.getParameter("name");
        String credit = req.getParameter("credit");*/
        //1.封装所需数据page:当前页码 ;limit:每页的信息数 ;name:查找的课程名字 ;credit:查找的学分

        //调用位于service层的分页查找功能
        ResearchersQuery researchersQuery = MyBeanUtil.copyToBean(req, ResearchersQuery.class);
        System.out.println(researchersQuery);
        PageRusult pageResult = researchersService.selectByPage(researchersQuery);

        JSONUtil.toJSON(resp, pageResult);

    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("ResearchersServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equals(code)){
            Result result = new Result(1,"验证码错误");
            JSONUtil.toJSON(resp, result);
            return;
        }
        Researchers researchers = researchersService.login(name,password);
        System.out.println(researchers);
        if(researchers == null){
            JSONUtil.toJSON(resp,Result.error("登陆失败"));
            return;
        }
        //autoLogin不为空说明勾选了“记住密码”
        String autoLogin = req.getParameter("autoLogin");
        if (autoLogin != null && !"".equals(autoLogin)){
            //下面是添加cookie的代码
            //cookie是以键值对的形式存在
            Cookie cookie = new Cookie("autoLogin",researchers.getName()+"&"+researchers.getPassword());
            //设置cookie存活时间和路径
            cookie.setMaxAge(60*60*24*7);//一周
            cookie.setPath(req.getContextPath());
            //cookie已经设置好了，把它添加到响应中，返回给浏览器吧
            resp.addCookie(cookie);

        }
        //这段代码即使不勾选自动登录也要执行的
        session.setAttribute("researchers", researchers);
        List<Auth> authList = authService.selectByRole(researchers.getRole());
        session.setAttribute("authList",authList);
        JSONUtil.toJSON(resp, Result.ok("登录成功"));
        //resp.sendRedirect("/JavaWeb");
    }
}
